package com.bootdo.app.controller;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.web.client.RestTemplate;

import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.wx.WeiXinUtil;
import com.bootdo.common.wx.WxConstants;
import com.bootdo.system.domain.WechatTemplate;
import com.bootdo.system.domain.WeixinUserList;
import com.bootdo.system.domain.WxOpenidInfo;

import net.sf.json.JSONObject;

public class DemoController {
	//微信模板接口
		 private final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
	public static void main(String[] args) throws ClientProtocolException, IOException {
		String accessToken = WeiXinUtil.getOauth2AccessToken2(WeiXinUtil.appid, WeiXinUtil.appSecret);
		//msgContent :消息内容 rwlx 投标类型 getFbsj 投标时间
//		getUserOpenIdList2(null,accessToken,msgContent,rwlx,allTaskById.getFbsj());
	}
	
	public WeixinUserList getUserOpenIdList2(String nextOpenid, String accessToken,String textCode,String tblx,String tbsj) {
        //用户openid列表信息
        WeixinUserList openIdListInfo = null;
        RestTemplate rest = new RestTemplate();
        synchronized(this){
            try {
                //循环获取用户openid列表
                do{
                    //微信公众号获取用户列表信息接口地址
                    String requestUrl = null;
                    if(StringUtils.isBlank(nextOpenid)){
                        requestUrl = new StringBuffer().append("https://api.weixin.qq.com/cgi-bin/user/get?access_token=").append(accessToken).toString();
                    }else {
                        requestUrl = new StringBuffer().append("https://api.weixin.qq.com/cgi-bin/user/get?access_token=")
                    .append(accessToken).append("&next_openid=").append(nextOpenid).toString();
                    }
                    openIdListInfo = rest.getForObject(requestUrl, WeixinUserList.class);
                    if(openIdListInfo != null && openIdListInfo.getErrcode() == 0){
                        //获取用户openid列表对象
                        WxOpenidInfo wxOpenidInfo = openIdListInfo.getData();
                        if(wxOpenidInfo != null){
                            List<String> openids = wxOpenidInfo.getOpenid();
                            if(openids != null && openids.size() > 0){
                                //生成数据的表头
                                StringBuffer text = new StringBuffer();
                                for (String openid : openids) {
                                    //生成数据的内容
//                                    text.append(openid+"\r\n");
//                                    System.out.println("openid============"+openid);
                                    //String text,String openId,String code
                            		String sendWxMsg = sendWxMsg(textCode,tblx, tbsj, openid, null,accessToken);
                            		System.out.println(sendWxMsg);
                                }
                                //写入txt文件中
//                                writeTxtFile(text.toString());
                            }
                            //拉取列表的最后一个用户的OPENID
                            nextOpenid = openIdListInfo.getNext_openid();
                        }
 
                    }else {
                        openIdListInfo.setErrcode(40000);
                        openIdListInfo.setErrmsg("获取关注用户列表失败");
                        return openIdListInfo ;
                    }
                }
                while (openIdListInfo.getCount() == 10000);
            } catch (Exception e) {
                openIdListInfo .setErrcode(40000);
                openIdListInfo .setErrmsg("获取用户列表失败");
                return openIdListInfo ;
            }
        }
        return openIdListInfo;
    }
	
	public  String sendWxMsg(String text,String tblx,String tbsj,String openId,String code,String accessToken) {
//		   String urlToken = "https://api.weixin.qq.com/cgi-bin/token";
//		   String tokenObj = HttpClientUtil.sendGet(urlToken, "grant_type=client_credential" + "&secret=" + WxConstants.APPSECRET + "&appid=" + WxConstants.APPID);
//		   JSONObject retToken = JSONObject.fromObject(tokenObj);
//		   String accessToken = String.valueOf(retToken.get("access_token"));
		  
		   TreeMap<String, TreeMap<String, String>> params = new TreeMap<String, TreeMap<String, String>>();
		   //根据具体模板参数组装
		   params.put("first", WechatTemplate.item("标注项目竞标信息", "#000000"));
		   //招标内容：{{keyword1.DATA}}项目类别：{{keyword2.DATA}}招标时间：{{keyword3.DATA}}
		   params.put("keyword1", WechatTemplate.item(text, "#000000"));
		   params.put("keyword2", WechatTemplate.item(tblx, "#000000"));
		   params.put("keyword3", WechatTemplate.item(tbsj, "#000000"));
		   params.put("remark", WechatTemplate.item("想要竞标项目的小伙伴，请尽快参与吧！", "#000000"));
		   WechatTemplate wechatTemplate = new WechatTemplate();
		   wechatTemplate.setTemplate_id(WxConstants.TEMPLATEID);
		   wechatTemplate.setTouser(openId);
//		   wechatTemplate.setUrl(url);
		   wechatTemplate.setData(params);
		   JSONObject json = JSONObject.fromObject(wechatTemplate);//将java对象转换为json对象
		   String sendData = json.toString();//将json对象转换为字符串
		  
		   TreeMap<String, String> treeMap = new TreeMap<String, String>();
		   treeMap.put("access_token", accessToken);
		   String retInfo = HttpUtil.doPost(SEND_TEMPLATE_MESSAGE_URL, treeMap, sendData);
		   return retInfo;
		 }

}
